<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理员主页</title>
    <!-- 引入Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- 引入Font Awesome图标 -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">
    <!-- 使用 Bootstrap 官方 CDN -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

    <!-- 或 cdnjs -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f5f5f5;
        }

        .navbar {
            background-color: #804D4E; /* 顶部大边框背景色 */
        }

        .navbar-brand {
            color: #fff !important;
            font-weight: bold;
        }

        .navbar-brand:hover {
            color: #f8f9fa !important; /* 悬停时的颜色 */
        }

        .sidebar {
            background-color: #fff;
            height: 100vh;
            box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
        }

        .sidebar .nav-link {
            color: #333;
            font-weight: 500;
            padding: 10px 15px;
            border-radius: 5px;
            margin-bottom: 5px;
            transition: all 0.3s ease;
        }

        .sidebar .nav-link:hover {
            background-color: #804D4E; /* 鼠标悬停背景色 */
            color: #fff !important;
        }

        .sidebar .nav-link.active {
            background-color: #804D4E; /* 选中状态背景色 */
            color: #fff !important;
        }

        .main-content {
            padding: 20px;
            background-color: #f5f5f5;
        }

        .card {
            margin-bottom: 20px;
            border: none;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }

        .card-header {
            background-color: #fff;
            border-bottom: 1px solid #eee;
        }

        .btn-primary {
            background-color: #804D4E;
            border-color: #804D4E;
        }

        .btn-primary:hover {
            background-color: #6a3d3e;
            border-color: #6a3d3e;
        }

        .hidden {
            display: none; /* 隐藏元素 */
        }
    </style>
</head>

<body>
<!-- 顶部导航栏 -->
<nav class="navbar navbar-expand-lg navbar-dark">
    <div class="container-fluid">
        <a class="navbar-brand" href="#">管理员主页</a>
        <ul class="navbar-nav ms-auto">
            <li class="nav-item dropdown">
                <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button"
                   data-bs-toggle="dropdown" aria-expanded="false">
                    <i class="fas fa-user-circle"></i> 管理员
                </a>
                <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
                    <li><a class="dropdown-item" href="#" onclick="showSection('settings')">个人设置</a></li>
                    <li>
                        <hr class="dropdown-divider">
                    </li>
                    <li><a class="dropdown-item" href="#">退出登录</a></li>
                </ul>
            </li>
        </ul>
    </div>
</nav>

<!-- 侧边栏和主内容区 -->
<div class="container-fluid">
    <div class="row">
        <!-- 侧边栏 -->
        <div class="col-md-2 sidebar">
            <div class="d-flex flex-column p-3">
                <ul class="nav flex-column">
                    <li class="nav-item">
                        <a class="nav-link" onclick="showSection('dashboard')">
                            <i class="fas fa-home me-2"></i> 仪表盘
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" onclick="showSection('category-management')">
                            <i class="fas fa-list-alt me-2"></i> 商品种类管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" onclick="showSection('product-management')">
                            <i class="fas fa-box me-2"></i> 商品管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" onclick="showSection('order-management')">
                            <i class="fas fa-shopping-cart me-2"></i> 订单管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" onclick="showSection('user-management')">
                            <i class="fas fa-users me-2"></i> 用户管理
                        </a>
                    </li>
                </ul>
            </div>
        </div>

        <!-- 主内容区 -->
        <div class="col-md-10 main-content">
            <!-- 仪表盘内容 -->
            <div id="dashboard-section" class="section">
                <h3>仪表盘</h3>
                <p>欢迎回来，管理员！</p>
            </div>

            <!-- 商品种类管理内容 -->
            <div id="category-management-section" class="section hidden">
                <h3>商品种类管理</h3>
                <div class="card">
                    <div class="card-header">
                        商品种类列表
                        <button class="btn btn-primary btn-sm float-end" onclick="openAddCategoryModal()">添加种类</button>
                    </div>
                    <div class="card-body">
                        <table class="table table-striped">
                            <thead>
                            <tr>
                                <th>ID</th>
                                <th>种类名称</th>
                                <th>图片URL</th>
                                <th>父级ID</th>
                                <th>父级名称</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody id="category-table-body">
                            <!-- 商品种类数据将通过JavaScript动态加载 -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- 添加商品种类模态框 -->
            <div class="modal fade" id="addCategoryModal" tabindex="-1" aria-labelledby="addCategoryModalLabel" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="addCategoryModalLabel">添加商品种类</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <form id="addCategoryForm">
                                <div class="mb-3">
                                    <label for="category-name" class="form-label">种类名称</label>
                                    <input type="text" class="form-control" id="category-name" required>
                                </div>
                                <div class="mb-3">
                                    <label for="category-imgurl" class="form-label">图片URL</label>
                                    <input type="text" class="form-control" id="category-imgurl">
                                </div>
                                <div class="mb-3">
                                    <label for="category-pid" class="form-label">父级分类ID</label>
                                    <input type="number" class="form-control" id="category-pid" value="0">
                                </div>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                            <button type="button" class="btn btn-primary" onclick="addCategory()">保存</button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 编辑商品种类模态框 -->
            <div class="modal fade" id="editCategoryModal" tabindex="-1" aria-labelledby="editCategoryModalLabel" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="editCategoryModalLabel">编辑商品种类</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <form id="editCategoryForm">
                                <input type="hidden" id="edit-category-id">
                                <div class="mb-3">
                                    <label for="edit-category-name" class="form-label">种类名称</label>
                                    <input type="text" class="form-control" id="edit-category-name" required>
                                </div>
                                <div class="mb-3">
                                    <label for="edit-category-imgurl" class="form-label">图片URL</label>
                                    <input type="text" class="form-control" id="edit-category-imgurl">
                                </div>
                                <div class="mb-3">
                                    <label for="edit-category-pid" class="form-label">父级分类ID</label>
                                    <input type="number" class="form-control" id="edit-category-pid">
                                </div>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                            <button type="button" class="btn btn-primary" onclick="updateCategory()">保存</button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 商品管理内容 -->
            <div id="product-management-section" class="section hidden">
                <h3>商品管理</h3>
                <div class="card">
                    <div class="card-header">
                        商品列表
                        <button class="btn btn-primary btn-sm float-end" onclick="openAddProductModal()">添加商品</button>
                    </div>
                    <div class="card-body">
                        <table class="table table-striped">
                            <thead>
                            <tr>
                                <th>ID</th>
                                <th>名称</th>
                                <th>价格</th>
                                <th>原价</th>
                                <th>描述</th>
                                <th>分类ID</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody id="product-table-body">
                            <!-- 商品数据将通过JavaScript动态加载 -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- 订单管理内容 -->
            <div id="order-management-section" class="section hidden">
                <h3>订单管理</h3>
                <div class="card">
                    <div class="card-header">
                        订单列表
                        <div class="input-group float-end" style="width: 300px;">
                            <input type="text" id="search-order-code" class="form-control" placeholder="输入订单号">
                            <button class="btn btn-primary" onclick="searchOrderByCode()">
                                <i class="fas fa-search"></i> 搜索
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <table class="table table-striped">
                            <thead>
                            <tr>
                                <th>订单号</th>
                                <th>收件人</th>
                                <th>价格</th>
                                <th>收货地址</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody id="order-table-body">
                            <!-- 订单数据将通过JavaScript动态加载 -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- 用户管理内容 -->
            <div id="user-management-section" class="section hidden">
                <h3>用户管理</h3>
                <div class="card">
                    <div class="card-header">
                        用户列表
                        <button class="btn btn-primary btn-sm float-end" onclick="openAddUserModal()">添加用户</button>
                    </div>
                    <div class="card-body">
                        <table class="table table-striped">
                            <thead>
                            <tr>
                                <th>ID</th>
                                <th>用户名</th>
                                <th>昵称</th>
                                <th>电话</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody id="user-table-body">
                            <!-- 用户数据将通过JavaScript动态加载 -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- 个人设置内容 -->
            <div id="settings-section" class="section hidden">
                <h3>个人设置</h3>
                <div class="card">
                    <div class="card-header">
                        管理员信息
                    </div>
                    <div class="card-body">
                        <form>
                            <div class="mb-3">
                                <label for="admin-username" class="form-label">用户名</label>
                                <input type="text" class="form-control" id="admin-username" value="admin">
                            </div>
                            <div class="mb-3">
                                <label for="admin-password" class="form-label">密码</label>
                                <input type="password" class="form-control" id="admin-password" value="********">
                            </div>
                            <button type="button" class="btn btn-primary">保存</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 添加商品模态框 -->
<div class="modal fade" id="addProductModal" tabindex="-1" aria-labelledby="addProductModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addProductModalLabel">添加商品</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="addProductForm">
                    <div class="mb-3">
                        <label for="product-name" class="form-label">名称</label>
                        <input type="text" class="form-control" id="product-name" required>
                    </div>
                    <div class="mb-3">
                        <label for="product-price" class="form-label">价格</label>
                        <input type="text" class="form-control" id="product-price" required>
                    </div>
                    <div class="mb-3">
                        <label for="product-oldprice" class="form-label">原价</label>
                        <input type="text" class="form-control" id="product-oldprice">
                    </div>
                    <div class="mb-3">
                        <label for="product-info" class="form-label">描述</label>
                        <textarea class="form-control" id="product-info" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="product-categoryid" class="form-label">分类ID</label>
                        <input type="text" class="form-control" id="product-categoryid" required>
                    </div>
                    <div class="mb-3">
                        <label for="product-state" class="form-label">状态</label>
                        <select class="form-control" id="product-state">
                            <option value="0">下架</option>
                            <option value="1">上架</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="product-defaultimg" class="form-label">默认图片URL</label>
                        <input type="text" class="form-control" id="product-defaultimg">
                    </div>
                    <div class="mb-3">
                        <label for="product-imgurl" class="form-label">图片URL</label>
                        <input type="text" class="form-control" id="product-imgurl">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="addProduct()">保存</button>
            </div>
        </div>
    </div>
</div>


<!-- 编辑用户模态框 -->
<div class="modal fade" id="editUserModal" tabindex="-1" aria-labelledby="editUserModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editUserModalLabel">编辑用户</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="editUserForm">
                    <input type="hidden" id="edit-user-id">
                    <div class="mb-3">
                        <label for="edit-username" class="form-label">用户名</label>
                        <input type="text" class="form-control" id="edit-username" required>
                    </div>
                    <div class="mb-3">
                        <label for="edit-nickname" class="form-label">昵称</label>
                        <input type="text" class="form-control" id="edit-nickname" required>
                    </div>
                    <div class="mb-3">
                        <label for="edit-password" class="form-label">密码</label>
                        <input type="password" class="form-control" id="edit-password" required>
                    </div>
                    <div class="mb-3">
                        <label for="edit-tel" class="form-label">电话</label>
                        <input type="text" class="form-control" id="edit-tel" required>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="updateUser()">保存</button>
            </div>
        </div>
    </div>
</div>





<!-- 修改订单状态模态框 -->
<div class="modal fade" id="updateOrderStatusModal" tabindex="-1" aria-labelledby="updateOrderStatusModalLabel"
     aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="updateOrderStatusModalLabel">修改订单状态</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form>
                    <div class="mb-3">
                        <label for="order-status" class="form-label">状态</label>
                        <select class="form-control" id="order-status">
                            <option value="已支付">已支付</option>
                            <option value="已下单">已下单</option>
                            <option value="已发货">已发货</option>
                            <option value="已收货">已收货</option>
                            <option value="已完成">已完成</option>
                            <option value="已失效">已失效</option>
                        </select>
                    </div>
                    <!-- 添加隐藏的输入框，用于存储订单 ID -->
                    <input type="hidden" id="order-id">
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="updateOrderStatus()">保存</button>
            </div>
        </div>
    </div>
</div>








<!-- 编辑商品模态框 -->
<div class="modal fade" id="editProductModal" tabindex="-1" aria-labelledby="editProductModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editProductModalLabel">编辑商品</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="editProductForm">
                    <input type="hidden" id="edit-product-id">
                    <div class="mb-3">
                        <label for="edit-product-name" class="form-label">名称</label>
                        <input type="text" class="form-control" id="edit-product-name" required>
                    </div>
                    <div class="mb-3">
                        <label for="edit-product-price" class="form-label">价格</label>
                        <input type="text" class="form-control" id="edit-product-price" required>
                    </div>
                    <div class="mb-3">
                        <label for="edit-product-oldprice" class="form-label">原价</label>
                        <input type="text" class="form-control" id="edit-product-oldprice">
                    </div>
                    <div class="mb-3">
                        <label for="edit-product-info" class="form-label">描述</label>
                        <textarea class="form-control" id="edit-product-info" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="edit-product-categoryid" class="form-label">分类ID</label>
                        <input type="text" class="form-control" id="edit-product-categoryid" required>
                    </div>
                    <div class="mb-3">
                        <label for="edit-product-state" class="form-label">状态</label>
                        <select class="form-control" id="edit-product-state">
                            <option value="0">下架</option>
                            <option value="1">上架</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="edit-product-defaultimg" class="form-label">默认图片URL</label>
                        <input type="text" class="form-control" id="edit-product-defaultimg">
                    </div>
                    <div class="mb-3">
                        <label for="edit-product-imgurl" class="form-label">图片URL</label>
                        <input type="text" class="form-control" id="edit-product-imgurl">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="updateProduct()">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 引入Bootstrap JS 和 jQuery -->
<!-- 使用 Google CDN -->


<!-- 或 Microsoft CDN -->
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // 显示对应模块
    // 加载商品种类数据
    async function loadCategories() {
        try {
            const response = await fetch('/api/categories');
            if (!response.ok) {
                throw new Error('网络响应失败');
            }
            const categories = await response.json();
            console.log('商品种类数据:', categories);

            const categoryTableBody = document.getElementById('category-table-body');
            categoryTableBody.innerHTML = ''; // 清空表格

            categories.forEach(category => {
                const row = document.createElement('tr');
                row.innerHTML = `
                <td>${category.id}</td>
                <td>${category.name}</td>
                <td>${category.imgUrl}</td>
                <td>${category.pid}</td>
                <td>${category.parent ? category.parent.name : '无'}</td>
                <td>
                    <button class="btn btn-sm btn-primary" onclick="openEditCategoryModal(${category.id}, '${category.name}', '${category.imgurl}', ${category.pid})">编辑</button>
                    <button class="btn btn-sm btn-danger" onclick="deleteCategory(${category.id})">删除</button>
                </td>
            `;
                categoryTableBody.appendChild(row);
            });
        } catch (error) {
            console.error('加载商品种类数据失败:', error);
            alert('加载商品种类数据失败，请稍后重试');
        }
    }

    // 打开添加商品种类模态框
    function openAddCategoryModal() {
        document.getElementById('addCategoryForm').reset();
        new bootstrap.Modal(document.getElementById('addCategoryModal')).show();
    }

    // 添加商品种类
    async function addCategory() {
        const name = document.getElementById('category-name').value.trim();
        const imgurl = document.getElementById('category-imgurl').value.trim();
        const pid = document.getElementById('category-pid').value;

        if (!name) {
            alert('请填写种类名称');
            return;
        }

        try {
            const response = await fetch('/api/categories', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ name, imgurl, pid, isdel: 0, inserttime: new Date(), updatetime: new Date() })
            });

            if (response.ok) {
                alert('商品种类添加成功');
                loadCategories(); // 重新加载商品种类数据
                new bootstrap.Modal(document.getElementById('addCategoryModal')).hide(); // 关闭模态框
            } else {
                alert('商品种类添加失败');
            }
        } catch (error) {
            console.error('添加商品种类失败:', error);
            alert('添加商品种类失败，请稍后重试');
        }
    }

    // 打开编辑商品种类模态框
    function openEditCategoryModal(id, name, imgurl, pid) {
        document.getElementById('edit-category-id').value = id;
        document.getElementById('edit-category-name').value = name;
        document.getElementById('edit-category-imgurl').value = imgurl;
        document.getElementById('edit-category-pid').value = pid;
        new bootstrap.Modal(document.getElementById('editCategoryModal')).show();
    }

    // 更新商品种类
    async function updateCategory() {
        const id = document.getElementById('edit-category-id').value;
        const name = document.getElementById('edit-category-name').value.trim();
        const imgurl = document.getElementById('edit-category-imgurl').value.trim();
        const pid = document.getElementById('edit-category-pid').value;

        if (!name) {
            alert('请填写种类名称');
            return;
        }

        try {
            const response = await fetch(`/api/categories/${id}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ name, imgurl, pid, updatetime: new Date() })
            });

            if (response.ok) {
                alert('商品种类更新成功');
                loadCategories(); // 重新加载商品种类数据
                new bootstrap.Modal(document.getElementById('editCategoryModal')).hide(); // 关闭模态框
            } else {
                alert('商品种类更新失败');
            }
        } catch (error) {
            console.error('更新商品种类失败:', error);
            alert('更新商品种类失败，请稍后重试');
        }
    }

    // 删除商品种类
    async function deleteCategory(id) {
        if (confirm('确定删除该商品种类吗？')) {
            try {
                const response = await fetch(`/api/categories/${id}`, {
                    method: 'DELETE'
                });

                if (response.ok) {
                    alert('商品种类删除成功');
                    loadCategories(); // 重新加载商品种类数据
                } else {
                    alert('商品种类删除失败');
                }
            } catch (error) {
                console.error('删除商品种类失败:', error);
                alert('删除商品种类失败，请稍后重试');
            }
        }
    }

    // 页面加载时加载商品种类数据
    document.addEventListener('DOMContentLoaded', function () {
        loadCategories();
    });
    // 加载商品数据
    async function loadProducts() {
        try {
            const response = await fetch('/api/products');
            if (!response.ok) {
                throw new Error('网络响应失败');
            }
            const products = await response.json();
            console.log('商品数据:', products);

            const productTableBody = document.getElementById('product-table-body');
            productTableBody.innerHTML = ''; // 清空表格

            products.forEach(product => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${product.id}</td>
                    <td>${product.name}</td>
                    <td>${product.price}</td>
                    <td>${product.oldprice}</td>
                    <td>${product.info}</td>
                    <td>${product.categoryid}</td>
                    <td>${product.state === 1 ? '上架' : '下架'}</td>
                    <td>
                        <button class="btn btn-sm btn-primary" onclick="openEditProductModal(${product.id}, '${product.name}', '${product.price}', '${product.oldprice}', '${product.info}', '${product.categoryid}', ${product.state}, '${product.defaultimg}', '${product.imgurl}')">编辑</button>
                        <button class="btn btn-sm btn-danger" onclick="deleteProduct(${product.id})">删除</button>
                    </td>
                `;
                productTableBody.appendChild(row);
            });
        } catch (error) {
            console.error('加载商品数据失败:', error);
            alert('加载商品数据失败，请稍后重试');
        }
    }

    // 打开添加商品模态框
    function openAddProductModal() {
        document.getElementById('addProductForm').reset();
        new bootstrap.Modal(document.getElementById('addProductModal')).show();
    }

    // 添加商品
    async function addProduct() {
        const name = document.getElementById('product-name').value.trim();
        const price = document.getElementById('product-price').value.trim();
        const oldprice = document.getElementById('product-oldprice').value.trim();
        const info = document.getElementById('product-info').value.trim();
        const categoryid = document.getElementById('product-categoryid').value.trim();
        const state = document.getElementById('product-state').value;
        const defaultimg = document.getElementById('product-defaultimg').value.trim();
        const imgurl = document.getElementById('product-imgurl').value.trim();

        if (!name || !price || !categoryid) {
            alert('请填写所有必填字段');
            return;
        }

        try {
            const response = await fetch('/api/products', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ name, price, oldprice, info, categoryid, state, defaultimg, imgurl })
            });

            if (response.ok) {
                alert('商品添加成功');
                loadProducts(); // 重新加载商品数据
                new bootstrap.Modal(document.getElementById('addProductModal')).hide(); // 关闭模态框
            } else {
                alert('商品添加失败');
            }
        } catch (error) {
            console.error('添加商品失败:', error);
            alert('添加商品失败，请稍后重试');
        }
    }

    // 打开编辑商品模态框
    function openEditProductModal(id, name, price, oldprice, info, categoryid, state, defaultimg, imgurl) {
        document.getElementById('edit-product-id').value = id;
        document.getElementById('edit-product-name').value = name;
        document.getElementById('edit-product-price').value = price;
        document.getElementById('edit-product-oldprice').value = oldprice;
        document.getElementById('edit-product-info').value = info;
        document.getElementById('edit-product-categoryid').value = categoryid;
        document.getElementById('edit-product-state').value = state;
        document.getElementById('edit-product-defaultimg').value = defaultimg;
        document.getElementById('edit-product-imgurl').value = imgurl;
        new bootstrap.Modal(document.getElementById('editProductModal')).show();
    }

    // 更新商品
    async function updateProduct() {
        const id = document.getElementById('edit-product-id').value;
        const name = document.getElementById('edit-product-name').value.trim();
        const price = document.getElementById('edit-product-price').value.trim();
        const oldprice = document.getElementById('edit-product-oldprice').value.trim();
        const info = document.getElementById('edit-product-info').value.trim();
        const categoryid = document.getElementById('edit-product-categoryid').value.trim();
        const state = document.getElementById('edit-product-state').value;
        const defaultimg = document.getElementById('edit-product-defaultimg').value.trim();
        const imgurl = document.getElementById('edit-product-imgurl').value.trim();

        if (!name || !price || !categoryid) {
            alert('请填写所有必填字段');
            return;
        }

        try {
            const response = await fetch(`/api/products/${id}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ name, price, oldprice, info, categoryid, state, defaultimg, imgurl })
            });

            if (response.ok) {
                alert('商品更新成功');
                loadProducts(); // 重新加载商品数据
                new bootstrap.Modal(document.getElementById('editProductModal')).hide(); // 关闭模态框
            } else {
                alert('商品更新失败');
            }
        } catch (error) {
            console.error('更新商品失败:', error);
            alert('更新商品失败，请稍后重试');
        }
    }

    // 删除商品
    async function deleteProduct(id) {
        if (confirm('确定删除该商品吗？')) {
            try {
                const response = await fetch(`/api/products/${id}`, {
                    method: 'DELETE'
                });

                if (response.ok) {
                    alert('商品删除成功');
                    loadProducts(); // 重新加载商品数据
                } else {
                    alert('商品删除失败');
                }
            } catch (error) {
                console.error('删除商品失败:', error);
                alert('删除商品失败，请稍后重试');
            }
        }
    }

    // 页面加载时默认显示仪表盘
    document.addEventListener('DOMContentLoaded', function () {
        showSection('dashboard');
    });
</script>






















<script>


    // 加载用户数据
    async function loadUsers() {
        try {
            const response = await fetch('/api/users');
            if (!response.ok) {
                throw new Error('网络响应失败');
            }
            const users = await response.json();
            console.log('用户数据:', users);

            const userTableBody = document.getElementById('user-table-body');
            userTableBody.innerHTML = ''; // 清空表格

            users.forEach(user => {
                const row = document.createElement('tr');
                row.innerHTML = `
                        <td>${user.id}</td>
                        <td>${user.username}</td>
                        <td>${user.nickname}</td>
                        <td>${user.tel}</td>
                        <td>
                            <button class="btn btn-sm btn-primary" onclick="openEditUserModal(${user.id}, '${user.username}', '${user.nickname}', '${user.tel}')">编辑</button>
                            <button class="btn btn-sm btn-danger" onclick="deleteUser(${user.id})">删除</button>
                        </td>
                    `;
                userTableBody.appendChild(row);
            });
        } catch (error) {
            console.error('加载用户数据失败:', error);
            alert('加载用户数据失败，请稍后重试');
        }
    }

    // 打开添加用户模态框
    function openAddUserModal() {
        document.getElementById('addUserForm').reset();
        new bootstrap.Modal(document.getElementById('addUserModal')).show();
    }

    // 添加用户
    async function addUser() {
        const username = document.getElementById('username').value.trim();
        const nickname = document.getElementById('nickname').value.trim();
        const password = document.getElementById('password').value.trim();
        const tel = document.getElementById('tel').value.trim();

        if (!username || !nickname || !password || !tel) {
            alert('请填写所有字段');
            return;
        }

        try {
            const response = await fetch('/api/users', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ username, nickname, password, tel })
            });

            if (response.ok) {
                alert('用户添加成功');
                loadUsers(); // 重新加载用户数据
                new bootstrap.Modal(document.getElementById('addUserModal')).hide(); // 关闭模态框
            } else {
                alert('用户添加失败');
            }
        } catch (error) {
            console.error('添加用户失败:', error);
            alert('添加用户失败，请稍后重试');
        }
    }

    // 打开编辑用户模态框
    function openEditUserModal(id, username, nickname, tel) {
        document.getElementById('edit-user-id').value = id;
        document.getElementById('edit-username').value = username;
        document.getElementById('edit-nickname').value = nickname;
        document.getElementById('edit-tel').value = tel;
        new bootstrap.Modal(document.getElementById('editUserModal')).show();
    }

    // 更新用户
    async function updateUser() {
        const id = document.getElementById('edit-user-id').value;
        const username = document.getElementById('edit-username').value.trim();
        const nickname = document.getElementById('edit-nickname').value.trim();
        const password = document.getElementById('edit-password').value.trim();
        const tel = document.getElementById('edit-tel').value.trim();

        if (!username || !nickname || !password || !tel) {
            alert('请填写所有字段');
            return;
        }

        try {
            const response = await fetch(`/api/users/${id}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ username, nickname, password, tel })
            });

            if (response.ok) {
                alert('用户更新成功');
                loadUsers(); // 重新加载用户数据
                new bootstrap.Modal(document.getElementById('editUserModal')).hide(); // 关闭模态框
            } else {
                alert('用户更新失败');
            }
        } catch (error) {
            console.error('更新用户失败:', error);
            alert('更新用户失败，请稍后重试');
        }
    }

    // 删除用户
    async function deleteUser(id) {
        if (confirm('确定删除该用户吗？')) {
            try {
                const response = await fetch(`/api/users/${id}`, {
                    method: 'DELETE'
                });

                if (response.ok) {
                    alert('用户删除成功');
                    loadUsers(); // 重新加载用户数据
                } else {
                    alert('用户删除失败');
                }
            } catch (error) {
                console.error('删除用户失败:', error);
                alert('删除用户失败，请稍后重试');
            }
        }
    }

    // 页面加载时加载用户数据
    document.addEventListener('DOMContentLoaded', function () {
        loadUsers();
    });
</script>











<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // 显示对应模块
    function showSection(sectionId) {
        console.log('showSection 函数被调用，sectionId:', sectionId);
        document.querySelectorAll('.section').forEach(section => {
            section.classList.add('hidden');
        });
        document.getElementById(`${sectionId}-section`).classList.remove('hidden');

        // 动态加载数据
        if (sectionId === 'order-management') {
            console.log('加载订单数据');
            loadOrders();
        }else if (sectionId === 'product-management') {
            loadProducts();
        }
    }

    // 加载订单数据
    async function loadOrders() {
        console.log('loadOrders 函数被调用');
        try {
            const response = await fetch('/api/orders');
            if (!response.ok) {
                throw new Error('网络响应失败');
            }
            const orders = await response.json();
            console.log('订单数据:', orders);

            const orderTableBody = document.getElementById('order-table-body');
            orderTableBody.innerHTML = ''; // 清空表格

            orders.forEach(order => {
                const row = document.createElement('tr');
                row.innerHTML = `
                        <td>${order.code}</td>
                        <td>${order.userid}</td>
                        <td>${order.money}</td>
                        <td>${order.orderaddress}</td>
                        <td>${order.state}</td>
                        <td>
                            <button class="btn btn-sm btn-primary" onclick="openUpdateOrderModal('${order.id}', '${order.state}')">编辑</button>
                            <button class="btn btn-sm btn-danger" onclick="deleteOrder('${order.id}')">删除</button>
                        </td>
                    `;
                orderTableBody.appendChild(row);
            });
        } catch (error) {
            console.error('加载订单数据失败:', error);
        }
    }

    // 打开修改订单状态模态框
    function openUpdateOrderModal(orderId, currentStatus) {
        document.getElementById('order-id').value = orderId; // 设置订单ID
        document.getElementById('order-status').value = currentStatus; // 设置当前状态
        new bootstrap.Modal(document.getElementById('updateOrderStatusModal')).show();
    }

    // 更新订单状态
    async function updateOrderStatus() {
        const orderId = document.getElementById('order-id').value;
        const status = document.getElementById('order-status').value;

        try {
            const response = await fetch(`/api/orders/${orderId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ state: status })
            });

            if (response.ok) {
                alert('订单状态更新成功');
                loadOrders(); // 重新加载订单数据
                new bootstrap.Modal(document.getElementById('updateOrderStatusModal')).hide(); // 关闭模态框
            } else {
                alert('订单状态更新失败');
            }
        } catch (error) {
            console.error('更新订单状态失败:', error);
        }
    }

    // 删除订单
    async function deleteOrder(orderId) {
        if (confirm('确定删除该订单吗？')) {
            try {
                const response = await fetch(`/api/orders/${orderId}`, {
                    method: 'DELETE'
                });

                if (response.ok) {
                    alert('订单删除成功');
                    loadOrders(); // 重新加载订单数据
                } else {
                    alert('订单删除失败');
                }
            } catch (error) {
                console.error('删除订单失败:', error);
            }
        }
    }

    // 根据订单号搜索订单
    async function searchOrderByCode() {
        const code = document.getElementById('search-order-code').value.trim();
        if (!code) {
            alert('请输入订单号');
            return;
        }

        try {
            const response = await fetch(`/api/orders/search?code=${code}`);
            if (!response.ok) {
                throw new Error('网络响应失败');
            }
            const order = await response.json(); // 接收单个订单
            console.log('搜索到的订单数据:', order);

            const orderTableBody = document.getElementById('order-table-body');
            orderTableBody.innerHTML = ''; // 清空表格

            if (!order) {
                orderTableBody.innerHTML = `
                <tr>
                    <td colspan="6" class="text-center">未找到相关订单</td>
                </tr>
            `;
                return;
            }

            // 渲染单个订单
            const row = document.createElement('tr');
            row.innerHTML = `
            <td>${order.code}</td>
            <td>${order.userid}</td>
            <td>${order.money}</td>
            <td>${order.orderaddress}</td>
            <td>${order.state}</td>
            <td>
                <button class="btn btn-sm btn-primary" onclick="openUpdateOrderModal('${order.id}', '${order.state}')">编辑</button>
                <button class="btn btn-sm btn-danger" onclick="deleteOrder('${order.id}')">删除</button>
            </td>
        `;
            orderTableBody.appendChild(row);
        } catch (error) {
            console.error('搜索订单失败:', error);
            alert('搜索订单失败，请稍后重试');
        }
    }








    // 页面加载时默认显示仪表盘
    document.addEventListener('DOMContentLoaded', function () {
        showSection('dashboard');
    });
</script>
</body>

</html>